﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using IotS.Core.Helpers;

namespace IotS.DeviceHub.Hub
{
    public class MessageHub
    {
        private static readonly QueuePub _pub;

        static MessageHub()
        {
            _pub = new QueuePub();
        }

        public static async Task<string> CallAsync(string deviceKey, string command, string param = null, int timeout = 10)
        {
            var id = GenerateCheckCode(5);
            var message = new Command
            {
                Cmd = command,
                Parameter = param,
                Device = deviceKey,
                Id = id
            };

            _pub.SendTo(message);

            var start = DateTime.Now;

            return await Task.Run(async () =>
            {
                var result = "";
                while (true)
                {
                    if ((DateTime.Now - start).Seconds >= timeout)
                        break;
                    await Task.Delay(50);
                    result = RedisHelper.Get(id);
                    if (result != null)
                        break;
                }
                return result ?? "no response";
            });
        }

        /// <summary>
        /// 生成随机字母字符串(数字字母混和)
        /// </summary>
        /// <param name="codeCount">待生成的位数</param>
        /// <returns>生成的字母字符串</returns>
        private static string GenerateCheckCode(int codeCount)
        {
            var rep = 0;
            var str = string.Empty;
            var num2 = DateTime.Now.Ticks + rep;
            rep++;
            var random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
            for (var i = 0; i < codeCount; i++)
            {
                char ch;
                var num = random.Next();
                if ((num % 2) == 0)
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                else
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                str = str + ch.ToString();
            }
            return str;
        }
    }
}
